package com.seo.controller.lightpay;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.seo.pojo.ReturnBody;
import com.seo.resolver.DefiniteException;
import com.seo.service.lightpay.impl.LightPayAlipayServiceImpl;
import com.seo.service.lightpay.sdk.LightPayAlipayService;
import com.seo.utils.ClientConst;
import com.seo.utils.CommonUtil;
import com.seo.utils.DateUtil;
import com.seo.utils.Jurisdiction;
import com.seo.utils.alipay.AlipayConfig;
import com.seo.utils.alipay.AlipayUtil;
import com.seo.utils.alipay.LightPayCashierAlipay;

import lombok.extern.slf4j.Slf4j;

/**
 * 支付回调Controller <br/>
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/lightpay/")
public class LightPayController {

	@Autowired
	private AlipayUtil alipayUtil;

	@Autowired
	private LightPayAlipayService lightPayAlipayService;

	/**
	 * 支付宝支付结果 <br/>
	 * 
	 * @author shibeilei
	 * @version 2019.11.19 11:40
	 */
	@RequestMapping(value = "result/alipay/{payType}/{userId}")
	public String alipay(@PathVariable("payType") String payType, @PathVariable("userId") Integer userId,
			HttpServletRequest request, HttpServletResponse response) {
		String tradeId = CommonUtil.getUUID();
		log.info("[{}]-【支付宝支付结果】-【开始】", tradeId);
		log.info("[{}]-【支付宝支付结果】-【校验参数】", tradeId);
		if (!LightPayCashierAlipay.AlipayType.isExists(payType)) {
			log.error("[{}]-【支付宝支付结果】-【支付类型不存在】", tradeId);
			return result(false, request);
		}
		if (userId == null || userId < 0) {
			log.error("[{}]-【支付宝支付结果】-【用户ID不能为空】", tradeId);
			return result(false, request);
		}

		Map<String, String> params = new HashMap<String, String>();

		try {

			Map<String, String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}
			log.info("[{}]-【支付宝支付结果】-【验证参数】", tradeId);
			AlipayConfig ac = lightPayAlipayService.getAlipayConfig(payType, userId);
			if (ac == null) {
				log.error("[{}]-【支付宝支付结果】-【支付宝配置不存在】", tradeId);
				return result(false, request);
			}
			alipayUtil.getReturnResult(params, ac);

			return result(true, request);
		} catch (Exception e) {
			log.error("[{}]-【支付宝支付结果】-【返回：fail】-【异常-[{}]】", tradeId, e);
			return result(false, request);
		}

	}

	public String result(boolean result, HttpServletRequest request) {
		request.setAttribute("result", result);
		return "lightpay/result";
	}

	@RequestMapping(value = "alipayConfigList")
	public String alipayConfigList(@RequestParam Map<String, Object> params, HttpServletRequest request,
			HttpSession session) {
		log.info("获取支付宝配置...");
		ReturnBody rb = ReturnBody.init();
		if (!Jurisdiction.roleCode("proxy")) {
			log.error("未开通代理功能，请联系管理员");
			throw new DefiniteException("未开通代理功能，请联系管理员");
		}
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);

		params.put("userId", userId);
		params.put("roleCode", "proxy");
		rb.run(lightPayAlipayService.getAlipayConfigList(params));
		request.setAttribute("page", rb.get("page"));

		return "lightpay/alipay/configList";

	}

	@ResponseBody
	@RequestMapping("/save")
	public ReturnBody save(@RequestBody AlipayConfig ac) {
		return lightPayAlipayService.save(ac, "proxy");
	}

	@ResponseBody
	@RequestMapping("/updateState")
	public ReturnBody updateState(Integer id, String state) {
		return lightPayAlipayService.updateState(id, state);
	}

}
